package com.testing.sunnycommon.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.testing.sunnycommon.model.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Classname SunnyAccessDeniedHandler
 * @Description 权限校验失败的时候的回调函数。
 * @Date 2023/6/30 22:36
 * @Created by 特斯汀Roy
 */
@Component
public class SunnyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=utf-8");
        Result result = Result.fail(401, "权限校验未通过", null);
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(result));
        writer.flush();
        writer.close();

    }
}
